<template>

    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="dataForm.type">
          <el-radio v-for="(type, index) in dataForm.typeList" :label="index" :key="index">{{ type }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="dataForm.typeList[dataForm.type] + '名称'" prop="name">
        <el-input v-model="dataForm.name" :placeholder="dataForm.typeList[dataForm.type] + '名称'"></el-input>
      </el-form-item>
      <el-form-item label="上级菜单" prop="parentName">
        <el-popover
            :width="300"
          ref="menuListPopover"
          placement="bottom-start"
          trigger="click">
          <template #default>
            <el-tree
            :data="menuList"
            :props="menuListTreeProps"
            node-key="menuId"
            ref="menuListTree"
            @current-change="menuListTreeCurrentChangeHandle"
            :default-expand-all="true"
            :highlight-current="true"
            :expand-on-click-node="false">
          </el-tree>
          </template>
          <template #reference>
              <el-input v-model="dataForm.parentName" v-popover:menuListPopover :readonly="true" placeholder="点击选择上级菜单" class="menu-list__input"></el-input>
          </template>
        </el-popover>
      </el-form-item>
      <el-form-item v-if="dataForm.type === 1" label="菜单路由" prop="url">
        <el-input v-model="dataForm.url" placeholder="菜单路由"></el-input>
      </el-form-item>
      <el-form-item v-if="dataForm.type !== 0" label="授权标识" prop="perms">
        <el-input v-model="dataForm.perms" placeholder="多个用逗号分隔, 如: user:list,user:create"></el-input>
      </el-form-item>
      <el-form-item v-if="dataForm.type !== 2" label="排序号" prop="orderNum">
        <el-input-number v-model="dataForm.orderNum" controls-position="right" :min="0" label="排序号"></el-input-number>
      </el-form-item>
      <el-form-item v-if="dataForm.type !== 2" label="菜单图标" prop="icon">
        <el-row>
          <el-col :span="22">
            <el-popover
              ref="iconListPopover"
              trigger="click"
              width="600"
              popper-class="mod-menu__icon-popover">
                <template #default>
                    <div class="mod-menu__icon-inner">
                        <div class="mod-menu__icon-list">
                            <el-icon v-for="(item, index) in iconList"
                            :key="index"
                            :size="20"
                            @click="iconActiveHandle(item)"
                            class="menu_icont"
                            :class="{ 'is-active': item === dataForm.icon }"><component :is="item" /></el-icon>
                        </div>
                    </div>
                </template>
                <template #reference>
                    <el-input v-model="dataForm.icon" v-popover:iconListPopover :readonly="true" placeholder="菜单图标名称" class="icon-list__input"></el-input>
                </template>
            </el-popover>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <span slot="footer" class="text-right">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit(dataFormRef)">确定</el-button>
    </span>
</template>

<script setup>
import { treeDataTranslate } from '@/utils'
import { onMounted, reactive, ref } from 'vue';
import {sellectMenus, getMenuInfo, setMenu} from '@/server/manage/sys.js'
import {ElMessage, ElDialog, ElButton, ElForm, ElFormItem, ElRow, ElCol, ElTooltip, ElInput, ElPopover, ElInputNumber, ElTree, ElRadioGroup, ElRadio, ElIcon  } from 'element-plus'
//   import Icon from '@/icons'
const props = defineProps(['id'])
const emit = defineEmits(['refreshDataList'])
const visible = ref(false)
const dataFormRef = ref()
const menuListTree = ref()
const menuListPopover= ref()
const dataForm = reactive({
    id: 0,
    type: 1,
    typeList: ['目录', '菜单', '按钮'],
    name: '',
    parentId: 0,
    parentName: '',
    url: '',
    perms: '',
    orderNum: 0,
    icon: '',
})
const iconList = ref(JSON.parse(localStorage.icons))
const validateUrl = (rule, value, callback) => {
    if (dataForm.type === 1 && !/\S/.test(value)) {
        callback(new Error('菜单URL不能为空'))
    } else {
        callback()
    }
}
const dataRule = reactive({
    name: [
        { required: true, message: '菜单名称不能为空', trigger: 'blur' }
    ],
    parentName: [
        { required: true, message: '上级菜单不能为空', trigger: 'change' }
    ],
    url: [
        { validator: validateUrl, trigger: 'blur' }
    ]
}) 
const menuList = ref([])
const menuListTreeProps =reactive({
    label: 'name',
    children: 'children'
}) 
const init = (id) => {
    dataForm.id = props.id || 0
    sellectMenus().then((data) => {
        menuList.value = treeDataTranslate(data.menuList, 'menuId')
    }).then(() => {
        visible.value = true
        // dataFormRef.value.resetFields()
    }).then(() => {
        if (!dataForm.id) {
        // 新增
            menuListTreeSetCurrentNode()
        } else {
        // 修改
            getMenuInfo(dataForm.id).then(({menu}) => {
                Object.assign(dataForm, menu)
                dataForm.id = menu.menuId
                menuListTreeSetCurrentNode()
            })
        }
    })
}
onMounted(() => {
    init()
})
// 菜单树选中
const menuListTreeCurrentChangeHandle = (data, node) =>{
    dataForm.parentId = data.menuId
    dataForm.parentName = data.name
}
// 菜单树设置当前选中节点
const menuListTreeSetCurrentNode = () => {
    menuListTree.value.setCurrentKey(dataForm.parentId)
    dataForm.parentName = (menuListTree.value.getCurrentNode() || {})['name']
}
// 图标选中
const iconActiveHandle = (iconName) => {
    dataForm.icon = iconName
}
// 表单提交
const dataFormSubmit = (formEl) => {
    if (!formEl) return
    formEl.validate( async(valid) => {
        if (valid) {
            dataForm.menuId = dataForm.id || undefined
            setMenu(dataForm, dataForm.id ?'update': 'save' ).then(res => {
                visible.value = false
                emit('refreshDataList')
                ElMessage({ message: "操作成功！", type: 'success'})
            })
        }
    })
}
</script>
<style scoped>
.menu_icont{
    margin: 6px;
}
.mod-menu__icon-inner{
  height: 260px;
  overflow: auto;
}
</style>